<template>
  <div id="components-layout-demo-basic">
    <!-- 考试id{{ id }} 倒计时{{ countDown }}
    <a-card v-for="(item, index) in data.testQuestions" :key="index">
      {{ item }}
    </a-card> -->
    <a-layout>
      <a-layout-sider
        width="350"
        :style="{
          overflow: 'auto',
          height: '100vh',
          position: 'fixed',
          left: 0
        }"
        ><a-card style="height:100%;">
          <!-- 倒计时 -->
          <a-statistic-countdown
            title="考试倒计时结束会强制提交试卷"
            :value="deadline"
            style="margin-right: 50px"
            @finish="onFinish"
          />
          <!-- 考生信息 -->
          <div style="margin-top:20px">
            <div style="width:50px;float:left">
              <a-avatar :src="profile.avatar" :size="51" icon="user" />
            </div>
            <div
              style="width:230px;float:left;text-align:left;margin-left:15px"
            >
              <p>{{ data.profile.className }}{{ data.profile.major }}</p>
              <p>考生姓名：{{ data.profile.name }}</p>
              <p>考生学号：{{ data.profile.code }}</p>
            </div>
            <div style="clear:both"></div>
          </div>
          <!-- 试卷信息 -->
          <div style="text-align:left;margin-top:40px">
            <a-statistic
              title="完成情况"
              :value="finishNumber"
              class="demo-class"
            >
              <template #suffix>
                <span
                  style="    color: rgba(0, 0, 0, 0.85);
    font-size: 24px;font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
}"
                >
                  / {{ data.testInformation[2].total }}</span
                >
              </template>
            </a-statistic>
            <a-tag
              v-for="(item, index) in data.testQuestions"
              :key="index"
              :id="'q' + index"
              color="blue"
              style="height:36px;width:36px;margin-top:6px;cursor:pointer;line-height:36px;text-align:center;font-size:16px"
              >{{ index + 1 }}
            </a-tag>
          </div>
          <!-- 考试须知 -->
          <div style="text-align:left;margin-top:40px">
            <a-popconfirm
              title="提交之后无法修改试卷，是否确认提交?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="postExam"
            >
              <a-button size="large" type="primary">提交试卷</a-button>
            </a-popconfirm>
          </div>
        </a-card>
      </a-layout-sider>
      <a-layout :style="{ marginLeft: '350px' }">
        <a-layout-header :style="{ textAlign: 'center' }">
          <p style="font-size:24px;">本场考试：{{ data.testName }}</p>
          <p>考试注意事项：图片可以点击放大</p>
        </a-layout-header>
        <a-layout-content
          :style="{ margin: '24px 16px 0', overflow: 'initial' }"
        >
          <div
            :style="{
              padding: '24px',
              background: '#fff'
            }"
          >
            <a-card
              v-for="(item, index) in data.testQuestions"
              style="text-align:left;font-size:16px"
              :key="index"
            >
              <!-- 题目描述 -->
              <div>
                <!-- 填空题 -->
                <a-tag
                  style="font-size:15px"
                  color="blue"
                  v-if="item.type == '填空题'"
                >
                  填空题：{{ item.score }}分
                </a-tag>
                <!-- 单选题 -->
                <a-tag
                  style="font-size:15px"
                  color="green"
                  v-if="item.type == '单选题'"
                >
                  单选题：{{ item.score }}分
                </a-tag>
                <!-- 多选题 -->
                <a-tag
                  style="font-size:15px"
                  color="orange"
                  v-if="item.type == '多选题'"
                >
                  多选题：{{ item.score }}分
                </a-tag>
                <!-- 问答题 -->
                <a-tag
                  style="font-size:15px"
                  color="pink"
                  v-if="item.type == '问答题'"
                >
                  问答题：{{ item.score }}分
                </a-tag>
                <!-- 判断题 -->
                <a-tag
                  style="font-size:15px"
                  color="red"
                  v-if="item.type == '判断题'"
                >
                  判断题：{{ item.score }}分
                </a-tag>
                <span v-if="item.type != '填空题'"
                  ><span style="font-size:30px">{{ index + 1 }}</span
                  >.{{ item.name }}</span
                >
                <span v-if="item.type == '填空题'"
                  ><span style="font-size:30px">{{ index + 1 }}</span
                  >.
                  <span v-for="(v, k) in item.name" :key="k"
                    ><span v-if="v != ''">{{ v }}</span>
                    <span v-else>{{ "( )" }}</span></span
                  ></span
                >
              </div>
              <!-- 图片 -->
              <div :id="index + 1">
                <div v-if="item.questionImg != null" style="width:100%;">
                  <div v-for="(imgs, idx) in item.questionImg" :key="idx">
                    <div
                      class="media questionImg"
                      style="width:150px;height:150px;float:left;"
                    >
                      <a
                        href="#"
                        class="media-content"
                        @click="showImg(imgs)"
                        :style="{ 'background-image': 'url(' + imgs + ')' }"
                      ></a>
                    </div>
                  </div>
                  <div style="clear:both"></div>
                </div>

                <a-modal
                  :visible="previewVisible"
                  :footer="null"
                  @cancel="handleCancel"
                >
                  <img alt="example" style="width: 100%" :src="previewImage" />
                </a-modal>
              </div>
              <!-- 单选/多选选项 判断题 -->
              <div
                v-if="
                  item.type == '单选题' ||
                    item.type == '多选题' ||
                    item.type == '判断题'
                "
              >
                <!-- 单选题 -->
                <a-radio-group
                  v-if="item.type == '单选题'"
                  v-model="form[index].keys"
                  @change="print(index, item.type)"
                >
                  <div v-for="(opt, idx) in item.questionOption" :key="idx">
                    <a-radio
                      style="margin-top:10px"
                      :value="String.fromCharCode(65 + idx)"
                    >
                      {{ String.fromCharCode(65 + idx) }}.{{ opt }}
                    </a-radio>
                  </div>
                </a-radio-group>
                <!-- 多选题 -->
                <a-checkbox-group
                  v-if="item.type == '多选题'"
                  v-model="form[index].keys"
                  @change="print(index, item.type)"
                >
                  <div v-for="(opt, idx) in item.questionOption" :key="idx">
                    <a-checkbox
                      style="margin-top:10px"
                      :value="String.fromCharCode(65 + idx)"
                    >
                      {{ String.fromCharCode(65 + idx) }}.{{ opt }}
                    </a-checkbox>
                  </div>
                </a-checkbox-group>
              </div>
              <!-- 判断题 -->
              <a-radio-group
                v-if="item.type == '判断题'"
                v-model="form[index].keys"
                @change="print(index, item.type)"
              >
                <div>
                  <a-radio value="正确">
                    正确
                  </a-radio>
                  <a-radio value="错误"> 错误 </a-radio>
                </div>
              </a-radio-group>
              <!-- 填空题 -->
              <div v-if="item.type == '填空题'">
                <div
                  v-for="(v, k) in item.cnt"
                  :key="k"
                  style="margin-top:10px;width:100px;float:left;margin-left:10px"
                >
                  <a-input
                    v-model="form[index].keys[k]"
                    @change="print(index, item.type)"
                    :placeholder="'空' + (k + 1)"
                  ></a-input>
                </div>
                <div style="clear:both"></div>
              </div>
              <!-- 问答题 -->
              <div v-if="item.type == '问答题'" style="margin-top:10px;">
                <a-input
                  v-model="form[index].keys"
                  @change="print(index, item.type)"
                  type="textarea"
                  placeholder="作答区域"
                  style="width:350px"
                ></a-input>
              </div>
            </a-card>
          </div>
        </a-layout-content>
        <!-- <a-layout-footer :style="{ textAlign: 'center' }">
          Ant Design ©2018 Created by Ant UED
        </a-layout-footer> -->
      </a-layout>
    </a-layout>
  </div>
</template>

<script>
import moment from "moment";
import { Modal, notification } from "ant-design-vue";

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  data() {
    return {
      id: null,
      data: {
        testQuestions: null,
        testInformation: [{}, {}, { total: null }],
        profile: { className: null }
      },
      st: null,
      deadline: 0,
      profile: null,
      previewVisible: false,
      previewImage: "",
      form: [], // 答案
      finishNumber: 0 // 完成的题目数量
    };
  },
  methods: {
    handleCancel() {
      this.previewVisible = false;
    },
    getExam() {
      this.$axios
        .get("/get/exam/detail/" + this.id, {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.data = res.data.data;
            this.data.testInformation = JSON.parse(this.data.testInformation);
            this.data.testQuestions = JSON.parse(this.data.testQuestions);
            this.data.examSetting = JSON.parse(
              this.data.testInformation[3].examSetting
            )[0];
            this.deadline = this.data.examSetting.examEndTime;
            this.data.profile = this.data.testInformation[3].profile;
            for (var i = 0; i < this.data.testQuestions.length; i++) {
              // init form
              if (
                this.form == null ||
                this.form.length != this.data.testQuestions.length
              ) {
                this.form.push({
                  id: this.data.testQuestions[i].qid,
                  isDone: false
                });
              }

              // 分割图片
              this.data.testQuestions[i].questionImg = this.data.testQuestions[
                i
              ].questionImg.split(",");
              // 处理单选多选的选项
              if (
                this.data.testQuestions[i].type == "多选题" ||
                this.data.testQuestions[i].type == "单选题"
              )
                this.data.testQuestions[
                  i
                ].questionOption = this.data.testQuestions[
                  i
                ].questionOption.split("[]");
              // 删除没有的图像
              if (this.data.testQuestions[i].questionImg[0] == "")
                this.data.testQuestions[i].questionImg = null;

              // 处理填空题问题
              if (this.data.testQuestions[i].type == "填空题") {
                this.data.testQuestions[i].name = this.data.testQuestions[
                  i
                ].name.split("[]");
                // 计算填空题多少个空格
                let cnt = 0;
                for (
                  let index = 0;
                  index < this.data.testQuestions[i].name.length;
                  index++
                ) {
                  if (this.data.testQuestions[i].name[index] == "") cnt++;
                }
                if (this.form[i].keys == null || this.form[i].keys.length == 0)
                  this.form[i].keys = new Array(cnt).fill(null);
                this.data.testQuestions[i].cnt = cnt;
              }
            }
            console.log(this.data);
            console.log("form:", this.form);
          } else {
            this.$message.error("获取失败");
          }
        });
    },
    onFinish() {
      this.$message.error("考试结束，已被系统自动提交");
      localStorage.removeItem("exam_t_tick");
      this.$router.push({ path: "/home/examination" });
      console.log("finished!");
    },
    check() {
      if (localStorage.getItem("exam_t_tick") == null) {
        this.$router.push({ path: "/home/examination" });
        return;
      }

      // 1. 获取cookie
      var cookie = localStorage.getItem("exam_t_tick");
      // 2. 获取cookie里的试卷id
      this.id = cookie.split(".")[0];
      this.st = moment(parseInt(cookie.split(".")[1])).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      // 3. 获取试卷
      this.getExam();

      // 4. 设置倒计时
      // var current = new Date().getTime();
      // var et = cookie.split(".")[2];

      // if (current > et) {
      //   this.$router.push({ path: "/home/examination" });
      //   return;
      // }
    },
    showImg(url) {
      this.previewImage = url;
      this.previewVisible = true;
    },
    print(idx, type) {
      if (type == "填空题") {
        var i = 0;
        for (; i < this.data.testQuestions[idx].cnt; i++) {
          console.log(this.form[idx].keys[i]);
          if (this.form[idx].keys[i] == null || this.form[idx].keys[i] == "") {
            this.form[idx].isDone = false;
            break;
          }
        }
        if (i >= this.data.testQuestions[idx].cnt) {
          // 改变idx对应的tag
          this.form[idx].isDone = true;
          document
            .getElementById("q" + idx)
            .setAttribute("class", "ant-tag ant-tag-has-color tag-green");
        } else {
          document
            .getElementById("q" + idx)
            .setAttribute("class", "ant-tag ant-tag-blue");
        }
      } else {
        if (
          this.form[idx].keys != null &&
          this.form[idx].keys != "" &&
          this.form[idx].keys.length != 0
        ) {
          this.form[idx].isDone = true;
          document
            .getElementById("q" + idx)
            .setAttribute("class", "ant-tag ant-tag-has-color tag-green");
        } else {
          this.form[idx].isDone = false;
          document
            .getElementById("q" + idx)
            .setAttribute("class", "ant-tag ant-tag-blue");
        }
      }
      let cnt = 0;
      for (let index = 0; index < this.form.length; index++) {
        if (this.form[index].isDone != false) {
          cnt++;
        }
      }
      this.finishNumber = cnt;
      localStorage.setItem("form", JSON.stringify(this.form));
      console.log("form", this.form);
    },
    checkAnswer() {
      let cnt = 0;
      for (let index = 0; index < this.form.length; index++) {
        if (this.form[index].isDone != false) {
          cnt++;
          document
            .getElementById("q" + index)
            .setAttribute("class", "ant-tag ant-tag-has-color tag-green");
        }
      }
      this.finishNumber = cnt;
    },
    getCookieInfo() {
      this.profile = JSON.parse(sessionStorage.getItem("userInfo"));
      if (localStorage.getItem("form") != null) {
        this.form = JSON.parse(localStorage.getItem("form"));
      }
    },
    postExam() {
      this.$axios
        .post(
          "/post/exam/data",
          {
            data: JSON.stringify(this.form),
            examId: this.id
          },
          {
            headers: {
              Authorization: localStorage.getItem("token")
            }
          }
        )
        .then(res => {
          if (res.data.code == 200) {
            this.$message.success(res.data.msg);
            localStorage.removeItem("form");
            localStorage.removeItem("exam_t_tick");
            this.$router.push({ path: "/home/examination" });
          } else {
            this.$message.error(res.data.msg);
          }
        });
    }
  },
  created() {
    this.getCookieInfo();
    this.check();
    setTimeout(() => {
      this.checkAnswer();
    }, 1500);
  }
};
</script>

<style scoped>
#components-layout-demo-basic {
  text-align: center;
}
#components-layout-demo-basic .ant-layout-header,
#components-layout-demo-basic .ant-layout-footer {
  background: #fff;
  color: #000;
}
#components-layout-demo-basic .ant-layout-footer {
  line-height: 1.5;
}
#components-layout-demo-basic .ant-layout-sider {
  background: #fff;
  color: #000;
  line-height: 120px;
}
#components-layout-demo-basic .ant-layout-content {
  background: #fff;
  color: #000;
  min-height: 120px;
  line-height: 120px;
}
#components-layout-demo-basic > .ant-layout {
  margin-bottom: 48px;
}
#components-layout-demo-basic > .ant-layout:last-child {
  margin: 0;
}
.media-content {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  border: 0;
  border-radius: inherit;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  background-color: rgba(120, 120, 120, 0.1);
}
.media {
  position: relative;
  display: block;
  overflow: hidden;
  padding: 0;
  -ms-flex-negative: 0;
  -webkit-flex-shrink: 0;
  flex-shrink: 0;
  border-radius: inherit;
}
.questionImg {
  border-radius: 10px;
  margin-right: 10px;
  margin-top: 10px;
}
.tag-green {
  background-color: rgb(135, 208, 104);
}
</style>
